package stpmproject.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import stpmproject.controller.viewobject.UserVO;
import stpmproject.dao.UserDOMapper;
import stpmproject.dao.UserPasswordDOMapper;
import stpmproject.dataobject.UserDO;
import stpmproject.dataobject.UserPasswordDO;
import stpmproject.error.BusinessException;
import stpmproject.error.EmBusinessError;
import stpmproject.service.UserService;
import stpmproject.service.model.UserModel;
import stpmproject.validator.ValidatorImpl;
import org.joda.time.DateTime;
import stpmproject.validator.ValidatorResult;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * encoding: utf-8
 *
 * @Author: kou dui
 * @Date: 2019/4/25 19:56
 * @software: IntelliJ IDEA
 * @file: UserServiceImpl
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    //自动装配一个UserDOMapper并调用其中的方法操作数据库
    private UserDOMapper userDOMapper;

    @Autowired
    //由于账户的密码分开存储，因此需要加入UserPasswordDOMapper
    private UserPasswordDOMapper userPasswordDOMapper;

    @Autowired
    //引入自己定义的校验规则
    private ValidatorImpl validator;

    @Override
    public UserModel getUserById(Integer id) {
        UserDO userDO=userDOMapper.selectByPrimaryKey(id);
        if(userDO==null){
            return null;
        }
        //通过用户id在密码库中获取用户的密码
        UserPasswordDO userPasswordDO=userPasswordDOMapper.selectByUserId(userDO.getId());
        return convertFromDataObject(userDO,userPasswordDO);
    }

    @Override
    public List<UserModel> listUser() {
        //在user_info中查找所有的用户信息，不包括密码
        List<UserDO> userDOList=userDOMapper.listUser();
        //使用stream api和lambda表达式实现用户列表
        List<UserModel> userModelList=userDOList.stream().map(userDO ->{
            UserModel userModel=this.convertFromDataObject(userDO);
            return userModel;
        }).collect(Collectors.toList());
        return userModelList;
    }

    @Override
    public UserModel getUserByTelphone(String telphone) {
        UserDO userDO=userDOMapper.selectByTelphone(telphone);
        if(userDO==null){
            return null;
        }
        return convertFromDataObject(userDO);
    }

    @Override
    public UserModel getUserByUserName(String userName) {
        UserDO userDO=userDOMapper.selectByUserName(userName);
        if(userDO==null){
            return null;
        }
        return convertFromDataObject(userDO);
    }

    @Override
    public boolean updateUser(UserModel userModel) throws BusinessException {
        if(userModel==null){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        ValidatorResult result=validator.validate(userModel);
        if(result.getHasErr()==true){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg());
        }
        UserDO userDO=convertFromModel(userModel);
        System.out.println("userModel.getRealname() = " + userModel.getRealname());
        int affectRows=userDOMapper.updateByPrimaryKeySelective(userDO);
        if(affectRows>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteUser(UserModel userModel) throws BusinessException {
        if(userModel==null){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        int affectRows=userDOMapper.deleteByPrimaryKey(userModel.getId());
        if(affectRows>0){
            return true;
        }
        return false;
    }

    @Override
    public void register(UserModel userModel) throws BusinessException {
        //判断是否为合法的注册对象
        if(userModel==null){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        //根据已经定义的校验规则校验参数的合法性
        ValidatorResult result=validator.validate(userModel);
        //如果有不合法的情况，返回具体的错误
        if(result.getHasErr()==true){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg());
        }
        //将UserModel转换为dataobject
        UserDO userDO=convertFromModel(userModel);
        //如果数据库中有重复的值就会报错，比如说用户名已经存在
        try{
            userDOMapper.insertSelective(userDO);
        }catch (DuplicateKeyException e){
            e.printStackTrace();
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"用户名已经注册");
        }
        //获取用户的id
        UserPasswordDO userPasswordDO=convertPasswordFromModel(userModel);
        //单独获取用户id
        userPasswordDO.setUserId(userDOMapper.selectByUserName(userModel.getUsername()).getId());
        //把用户的密码插入到密码库中
        userPasswordDOMapper.insertSelective(userPasswordDO);
        return;
    }
    private UserPasswordDO convertPasswordFromModel(UserModel userModel){
        if(userModel==null){
            return null;
        }
        UserPasswordDO userPasswordDO=new UserPasswordDO();
        //应当留意是否注入了明文密码
        BeanUtils.copyProperties(userModel,userPasswordDO);
        return userPasswordDO;
    }
    private UserDO convertFromModel(UserModel userModel){
        if(userModel==null){
            return null;
        }
        UserDO userDO=new UserDO();
        //复制相同的属性，没有的则跳过
        BeanUtils.copyProperties(userModel,userDO);
        return userDO;
    }

    @Override
    public UserModel validateLogin(String userName, String encrptPassword) throws BusinessException {
        //根据用户名查找用户
        UserDO userDO=userDOMapper.selectByUserName(userName);
        if(userDO==null){
            throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
        }
        UserPasswordDO userPasswordDO=userPasswordDOMapper.selectByUserId(userDO.getId());
        //对比数据库中的密码是否和经过加密后的参数相同
        if(!StringUtils.equals(encrptPassword,userPasswordDO.getEncrptPassword())){
            throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
        }
        UserModel userModel=convertFromDataObject(userDO,userPasswordDO);
        return userModel;
    }

    //方法重载
    private UserModel convertFromDataObject(UserDO userDO){
        if(userDO==null){
            return null;
        }
        UserModel userModel=new UserModel();
        BeanUtils.copyProperties(userDO,userModel);
        return userModel;
    }

    private UserModel convertFromDataObject(UserDO userDO,UserPasswordDO userPasswordDO){
        if(userDO==null){
            return null;
        }
        UserModel userModel=new UserModel();
        BeanUtils.copyProperties(userDO,userModel);
        if(userPasswordDO!=null){
            userModel.setEncrptPassword(userPasswordDO.getEncrptPassword());
        }
//        userModel.setBirthday(new Date(String.valueOf(userDO.getBirthday())));
//        userModel.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse((String.valueOf(userDO.getBirthday())));
        return userModel;
    }

    @Override
    public List<UserModel> listProgramer() {
        //在user_info中查找所有项目经理，不包括密码
        List<UserDO> userDOList=userDOMapper.listProgramer();
        //使用stream api和lambda表达式实现用户列表
        List<UserModel> userModelList=userDOList.stream().map(userDO ->{
            UserModel userModel=new UserModel();
            userModel.setUsername(userDO.getUsername());
            userModel.setRealname(userDO.getRealname());
            userModel.setRole(userDO.getRole());
            userModel.setEmail(userDO.getEmail());
            return userModel;
        }).collect(Collectors.toList());
        return userModelList;
    }

    @Override
    public List<UserModel> listDeveloper() {
        //在user_info中查找所有开发人员，不包括密码
        List<UserDO> userDOList=userDOMapper.listDeveloper();
        //使用stream api和lambda表达式实现用户列表
        List<UserModel> userModelList=userDOList.stream().map(userDO ->{
            UserModel userModel=new UserModel();
            userModel.setUsername(userDO.getUsername());
            userModel.setRealname(userDO.getRealname());
            userModel.setRole(userDO.getRole());
            userModel.setEmail(userDO.getEmail());
            return userModel;
        }).collect(Collectors.toList());
        return userModelList;
    }

    @Override
    public List<UserModel> listTester() {
        //在user_info中查找所有项目经理，不包括密码
        List<UserDO> userDOList=userDOMapper.listTester();
        //使用stream api和lambda表达式实现用户列表
        List<UserModel> userModelList=userDOList.stream().map(userDO ->{
            UserModel userModel=new UserModel();
            userModel.setUsername(userDO.getUsername());
            userModel.setRealname(userDO.getRealname());
            userModel.setRole(userDO.getRole());
            userModel.setEmail(userDO.getEmail());
            return userModel;
        }).collect(Collectors.toList());
        return userModelList;
    }
}
